package com.dhcc.bpm.common.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateException;
import cn.hutool.extra.template.TemplateUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * @ClassName TemplateConfig
 * @Description TODO
 * @Author Mlf
 * @Date 2020/3/27 13:03
 * @Version 1.0
 */
@Slf4j
public class TemplateConfig {

    public static void generate(String filePath,Map<String , Object> map,String ftlPath){
        TemplateEngine engine = TemplateUtil.createEngine(new cn.hutool.extra.template.TemplateConfig("templates", cn.hutool.extra.template.TemplateConfig.ResourceMode.CLASSPATH
        ));
        Template template = engine.getTemplate(ftlPath);
        try {
            genFile(new File(filePath),template,map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String generate(Map<String , Object> map,String ftlPath){
        TemplateEngine engine = TemplateUtil.createEngine(new cn.hutool.extra.template.TemplateConfig("templates", cn.hutool.extra.template.TemplateConfig.ResourceMode.CLASSPATH
        ));
        Template template = engine.getTemplate(ftlPath);
        try {
            return genString(template,map);
        } catch (IOException e) {
            log.error("ftl 加载出错!!",e);
            return null;
        }
    }
    private static String genString(Template template, Map<String, Object> map) throws IOException {
        try {
            return template.render(map);
        } catch (TemplateException e) {
            log.error("ftl 加载出错!!",e);
            return "";
        }
    }

    private static void genFile(File file, Template template, Map<String, Object> map) throws IOException {
        // 生成目标文件
        Writer writer = null;
        try {
            FileUtil.touch(file);
            writer = new FileWriter(file);
            template.render(map, writer);
        } catch (TemplateException | IOException e) {
            log.error("ftl 加载出错!!",e);
        } finally {
            if(writer!=null){
                writer.close();
            }
        }
    }
}
